package com.t309.tzy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(urlPatterns = {"/*"},filterName="EncodeFilter" ,
		initParams = {@WebInitParam(name = "encode", value = "utf-8")})
public class EncodeFilter implements Filter {
	private String encode=null;
	public void destroy() {
		encode=null;
	}
	/**
	 * 执行过滤操作
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if(null==request.getCharacterEncoding()){
			request.setCharacterEncoding(encode);
			response.setContentType("text/html;charset=utf8");
			System.out.println("过滤器设置请求的字符编码");
		}
		chain.doFilter(request, response);
	}

	/**
	 * 初始化
	 * @param filterConfig
	 * @throws ServletException
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		String encode=filterConfig.getInitParameter("encode");		
		if(this.encode==null){
			this.encode=encode;
		}
	}
}